package wangwenjun.phase2.concurrencypattern.eventbus.google.demo07;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import util.ThreadUtil;

import java.util.concurrent.Executors;

/**
 * @author ChangLiang
 * @date 2020/6/19
 */
@Slf4j
public class AppTest {

    /**
     * 传统的写法：这里可以直接就写一个OrderQueryService，接收请求 执行查询 处理返回结果
     *
     * 我们这里使用eventBus 把接收请求 和 处理返回结果 让OrderQueryAcceptor来处理
     * 而OrderQueryHandler来处理查询
     * 两者就进行了解耦
     */

    @Test
    @DisplayName("test sync")
    public void test(){
        final EventBus eventBus = new EventBus();
        OrderQueryAcceptor orderQueryAcceptor = new OrderQueryAcceptor(eventBus);
        eventBus.register(new OrderQueryHandler(eventBus));
        String orderNo = "1111";
        orderQueryAcceptor.queryOrder(orderNo);
        log.info("{} order query finish", this.getClass().getSimpleName());
    }

    @Test
    @DisplayName("test async")
    public void test2(){
        final EventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(10),(e,c)->{
            log.error(ThreadUtil.exceptionToString(e));
            log.error("event:{} eventBus:{} subscriber:{} method:{}",
                    c.getEvent(),
                    c.getEventBus(),
                    c.getSubscriber().getClass().getSimpleName(),
                    c.getSubscriberMethod().getName());
        });
        OrderQueryAcceptor orderQueryAcceptor = new OrderQueryAcceptor(eventBus);
        eventBus.register(new OrderQueryHandler(eventBus));
        String orderNo = "1111";
        orderQueryAcceptor.queryOrder(orderNo);
        log.info("{} order query finish", this.getClass().getSimpleName());
        /**
         * output:
         * [main] [INFO ] -- OrderQueryAcceptor do query the orderNo:1111
         * [main] [INFO ] -- AppTest order query finish
         * [pool-1-thread-1] [INFO ] -- OrderQueryHandler start query the orderNo:OrderQueryRequest{orderNo=1111}
         * 这里采用异步 导致回调OrderQueryAcceptor没有成功 主线程直接结束了
         */
    }
}
